package org.jeecg.modules.zcgl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgBaseController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysAnnouncement;
import org.jeecg.modules.zcgl.entity.CustomerBalanceChangesDetail;
import org.jeecg.modules.zcgl.entity.CustomerInfo;
import org.jeecg.modules.zcgl.entity.LeaseContractInfo;
import org.jeecg.modules.zcgl.service.ICustomerBalanceChangesDetailService;
import org.jeecg.modules.zcgl.service.ICustomerBalanceService;
import org.jeecg.modules.zcgl.service.ICustomerInfoService;
import org.jeecg.modules.zcgl.service.ILeaseContractInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 客户管理
 * @Author: jeecg-boot
 * @Date:   2020-06-17
 * @Version: V1.0
 */
@Api(tags="客户管理")
@RestController
@RequestMapping("/zcgl/customerInfo")
@Slf4j
public class CustomerInfoController extends JeecgBaseController<CustomerInfo, CustomerInfo, ICustomerInfoService> {
	@Autowired
	private ICustomerInfoService customerInfoService;
	@Autowired
	private ICustomerBalanceService balanceService;
	@Autowired
	private ILeaseContractInfoService leaseContractInfoService;
	@Autowired
	private ICustomerBalanceChangesDetailService iCustomerBalanceChangesDetailService;


	/**
	 * 分页列表查询
	 *
	 * @param customerInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "客户管理-分页列表查询")
	@ApiOperation(value="客户管理-分页列表查询", notes="客户管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(CustomerInfo customerInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CustomerInfo> queryWrapper = QueryGenerator.initQueryWrapper(customerInfo, req.getParameterMap());
		Page<CustomerInfo> page = new Page<CustomerInfo>(pageNo, pageSize);
		IPage<CustomerInfo> pageList = customerInfoService.page(page, queryWrapper);

//		LoginUser sysUser = JwtUtil.getLoginUser();
//		if (!jeecgPropertyConfig.getBaseDepartId().equalsIgnoreCase(sysUser.getCurrentCompanyId())){
//			pageList.getRecords().forEach(customer -> {
//				BigDecimal balance = balanceService.selectBalanceCustomerIdAndCompanyId(sysUser.getCurrentCompanyId(), customer.getId());
//				//暂存公司余额
//				customer.setTotalBalance(balance);
//			});
//		}
		return Result.ok(pageList);
	}

	/**
	 * 通过id查询余额变动明细
	 *
	 * @param
	 * @return
	 */
	@AutoLog(value = "客户管理-查询余额变动明细")
	@ApiOperation(value="客户管理-查询余额变动明细", notes="客户管理-查询余额变动明细")
	@GetMapping(value = "/queryBalanceDetailed")
	public Result<?> queryBalanceDetailed(CustomerBalanceChangesDetail customerBalanceChangesDetail,
										  HttpServletRequest req) {
		QueryWrapper<CustomerBalanceChangesDetail> queryWrapper = QueryGenerator.initQueryWrapper(customerBalanceChangesDetail, req.getParameterMap());
//		LambdaQueryWrapper<CustomerBalanceChangesDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//		lambdaQueryWrapper.eq(CustomerBalanceChangesDetail::getCustomerId,req.getParameterMap().get("customerId"));
//		lambdaQueryWrapper.orderByDesc(CustomerBalanceChangesDetail::getCreateTime);
		List<CustomerBalanceChangesDetail> list= iCustomerBalanceChangesDetailService.list(queryWrapper);
		List<HashMap<String,String>> result= new ArrayList<HashMap<String,String>>();
		HashMap<String,String> company=new HashMap<String,String>();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String detal="";
		for (CustomerBalanceChangesDetail l:list) {
			String changeType="";
			if(l.getChangesType()==2){
				changeType="-";
			}

			if(!company.containsKey(l.getCompanyId())){
				detal="";
				detal+="【变动时间："+sdf.format(l.getCreateTime())+"   "+"变动金额："+changeType+l.getChangesAmount()+"   "+"当前余额："+l.getNewBalance()+"   "+"变动说明："+l.getDescription()+"】\r";
				company.put(l.getCompanyId(),detal);
			}else{
				detal=company.get(l.getCompanyId());
				detal+="【变动时间："+sdf.format(l.getCreateTime())+"   "+"变动金额："+changeType+l.getChangesAmount()+"   "+"当前余额："+l.getNewBalance()+"   "+"变动说明："+l.getDescription()+"】\r";
				company.put(l.getCompanyId(),detal);
			}
		}

		for (Map.Entry<String, String> entry : company.entrySet()) {
			HashMap<String,String> balanceDetail=new HashMap<String,String>();
			balanceDetail.put("companyId",entry.getKey());
			balanceDetail.put("balanceDetailed",entry.getValue());
			result.add(balanceDetail);
		}

		return Result.ok(result);
	}


	/**
	 *   添加
	 *
	 * @param customerInfo
	 * @return
	 */
	@AutoLog(value = "客户管理-添加")
	@ApiOperation(value="客户管理-添加", notes="客户管理-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody CustomerInfo customerInfo) {
		String r = this.checkModel(customerInfo);
		if (r != null){
			return Result.error(r);
		}
		customerInfoService.save(customerInfo);
		return Result.ok("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param customerInfo
	 * @return
	 */
	@AutoLog(value = "客户管理-编辑")
	@ApiOperation(value="客户管理-编辑", notes="客户管理-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody CustomerInfo customerInfo) {
		String r = this.checkModel(customerInfo);
		if (r != null){
			return Result.error(r);
		}
		customerInfoService.updateById(customerInfo);
		return Result.ok("编辑成功!");
	}

	/**
	 *  预存款退款检测
	 * @param vo
	 * @return
	 */
	@AutoLog(value = "客户管理-预存款退款")
	@ApiOperation(value="客户管理-预存款退款", notes="客户管理-预存款退款")
	@PostMapping(value = "/balanceRefund")
	public Result<?> balanceRefund(@RequestBody CustomerBalanceChangesDetail vo) {
		LoginUser sysUser = JwtUtil.getLoginUser();
		//设置当前用户选择的公司ID为变更的公司余额
		vo.setCompanyId(sysUser.getCurrentCompanyId());
		customerInfoService.balanceRefund(vo);
		return Result.ok("预存款退款成功!");
	}

	/**
	 *  预存款退款检测
	 * @param vo
	 * @return
	 */
	@AutoLog(value = "客户管理-预存款退款检测")
	@ApiOperation(value="客户管理-预存款退款检测", notes="客户管理-预存款退款检测")
	@PostMapping(value = "/balanceRefundCheck")
	public Result<?> balanceRefundCheck(@RequestBody CustomerBalanceChangesDetail vo) {
		customerInfoService.balanceRefundCheck(vo);
		return Result.ok();
	}

	/**
	 * 检测实体验证
	 * @param entity
	 */
	private String checkModel(CustomerInfo entity){

//		if (StringUtils.isBlank(entity.getName())){
//			return "姓名/单位名称不能为空";
//		}
//		if (StringUtils.isBlank(entity.getCode())){
//			return "身份证号/信用代码不能为空";
//		}
//		if (StringUtils.isBlank(entity.getContactAddress())){
//			return "家庭住址/单位地址不能为空";
//		}
//		if (StringUtils.isBlank(entity.getPhone())){
//			return "联系电话不能为空";
//		}
		if (StringUtils.isNotBlank(entity.getLegalPersonIdCard())){
			entity.setLegalPersonIdCard(entity.getLegalPersonIdCard().toUpperCase());
		}

		if(StringUtils.isNotBlank(entity.getCode())){
			entity.setCode(entity.getCode().toUpperCase());
		}

		LambdaQueryWrapper<CustomerInfo> queryWrapper = new LambdaQueryWrapper<>();
		if (StringUtils.isNotBlank(entity.getId())){
			queryWrapper.ne(CustomerInfo::getId, entity.getId());
		}
		CustomerInfo customerInfo = new CustomerInfo();
		customerInfo.setCode(entity.getCode());
		customerInfo.setPhone(entity.getPhone());
		customerInfo.setName(entity.getName());
//		queryWrapper.eq(CustomerInfo :: getCode, entity.getCode());
		queryWrapper.setEntity(customerInfo);
		queryWrapper.last("LIMIT 1");
		CustomerInfo v = customerInfoService.getOne(queryWrapper);
		if (v != null){
			return  "【" + entity.getName() + "_" + entity.getPhone() + "_" + entity.getCode() + "】客户信息已存在！";
		}
		return null;
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "客户管理-通过id删除")
	@ApiOperation(value="客户管理-通过id删除", notes="客户管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		String customerSql = QueryGenerator.getCustomerSql(Arrays.asList(id));
		if (leaseContractInfoService.isHasByTo(new LambdaQueryWrapper<LeaseContractInfo>().apply(customerSql))){
			return Result.error("客户已签订过合同，不能删除！");
		}
		customerInfoService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "客户管理-批量删除")
	@ApiOperation(value="客户管理-批量删除", notes="客户管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> idList = Arrays.asList(ids.split(CommonConstant.DEFAULT_SEPARATOR));
		for (String id : idList) {
			String customerSql = QueryGenerator.getCustomerSql(Arrays.asList(id));
			if (leaseContractInfoService.isHasByTo(new LambdaQueryWrapper<LeaseContractInfo>().apply(customerSql))){
				return Result.error("有客户已签订过合同，不能删除！");
			}
		}
		this.customerInfoService.removeByIds(idList);
		return Result.ok("批量删除成功!");
	}


	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "客户管理-通过id查询")
	@ApiOperation(value="客户管理-通过id查询", notes="客户管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		CustomerInfo customerInfo = customerInfoService.getById(id);
		if(customerInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(customerInfo);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param customerInfo
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, CustomerInfo customerInfo) {
		return super.exportXls(request, customerInfo, CustomerInfo.class, "客户管理");
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, CustomerInfo.class);
	}

	@Override
	public List<CustomerInfo> exportList(List<CustomerInfo> list) {
		return list;
	}

	@Override
	public boolean importSave(CustomerInfo vo) {
		String checkStr = this.checkModel(vo);
		if (checkStr != null){
			throw new JeecgBootException(checkStr);
		}
		customerInfoService.save(vo);
		return true;
	}

}
